﻿using Senparc.Weixin.MP;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HANS.WeChat;
using HANS_WeChat.Base.Common;
using Senparc.Weixin.MP.MvcExtension;

namespace HANS_BackStageWeb.Areas.HANSWeChat.Controllers
{
    public class RegisterController : Controller
    {
        // GET: HANSWeChat/Register
        /// <summary>
        /// 成为开发者 然后写在微信公众号的开发链接 如：http://xuhuale.iask.in/wxsite/WeChatApi/Register
        /// </summary>
        /// <param name="signature">微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。</param>
        /// <param name="timestamp">时间戳</param>
        /// <param name="nonce">随机数</param>
        /// <param name="echostr">随机字符串</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("Index")]
        public ActionResult Get(string signature, string timestamp, string nonce, string echostr)
        {
            if (CheckSignature.Check(signature, timestamp, nonce, WeChatBaseInfo.Token))
            {
                return Content(echostr);
            }
            else
            {
                return Content("failed:" + signature + "," + Senparc.Weixin.MP.CheckSignature.GetSignature(timestamp, nonce, WeChatBaseInfo.Token) + "。如果您在浏览器中看到这条信息，表明此Url可以填入微信后台。");
            }
        }

        /// <summary>
        /// 所有微信公众号的业务处理入口
        /// </summary>
        /// <param name="postModel"></param>
        /// <param name="echostr"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionName("Index")]
        public ActionResult Post(Senparc.Weixin.MP.Entities.Request.PostModel postModel, string echostr)
        {

            if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, WeChatBaseInfo.Token))
            {
                return Content("参数出错");
            }
            postModel.Token = WeChatBaseInfo.Token;
            postModel.EncodingAESKey = WeChatBaseInfo.EncodingAESKey;
            postModel.AppId = WeChatBaseInfo.AppID;
            var messageHandler = new CustomMessageHandler(Request.InputStream, postModel);
            messageHandler.OmitRepeatedMessage = true;//启用消息去重功能
            messageHandler.Execute();
            return new FixWeixinBugWeixinResult(messageHandler);

        }
    }
}